package com.gdk.ksoft.ui.customers;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.CustomerAreaTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.ui.customers.models.CustomerInfoModel;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.extensions.StringUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONObject;

import java.io.InputStream;
import java.util.List;

/**
 * 新增客户页面
 */
public class NewCustomerActivity extends Activity {

    @ViewInject(R.id.pnewCustomer_etCustomerName)private EditText etCustomerName;//客户名称
    @ViewInject(R.id.pnewCustomer_etAbbreviation)private EditText etAbbrviation;//收货地址简称
    @ViewInject(R.id.pnewCustomer_etAddress)private EditText etAddress;//收货地址
    @ViewInject(R.id.pnewCustomer_etContractorName)private EditText etContractorName;//收货人名称
    @ViewInject(R.id.pnewCustomer_txtCustomerArea)private TextView txtCustomerArea;//所在地区
    @ViewInject(R.id.pnewCustomer_txtCustomerType)private TextView txtCustomerType;//客户类型
    @ViewInject(R.id.pnewCustomer_etCustomerConnectity)private EditText etConnectity;//收货人联系方式
    @ViewInject(R.id.pnewCustomer_etManagementArea)private EditText etManagementArea;//经营面积

    private CustomerInfoModel customerInfo = new CustomerInfoModel();//客户数据实体类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_customer);
        ViewUtils.inject(this);
        init(this);//初始化操作
    }

    /**
     * 界面视图控件点击事件
     * @param view
     */
    @OnClick(value = {R.id.pnewCustomer_txtSubmit})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pnewCustomer_txtSubmit:
                if(NetworkUtils.isNetAvailable(this)){
                    if(!checkArguments()) return;
                    customerInfo.customerName = etCustomerName.getText().toString();
                    customerInfo.addr = etAddress.getText().toString();
                    customerInfo.abbr = etAbbrviation.getText().toString();
                    customerInfo.contractor = etContractorName.getText().toString();
                    customerInfo.connectity = etConnectity.getText().toString();
                    customerInfo.addrArea = etManagementArea.getText().toString();
                    executeUploadWork(this);//启动数据上传工作
                }else{
                    Toast.makeText(this,"请检查网络状态!",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }

    /**
     * 启动数据上传工作
     */
    public void executeUploadWork(final Context ctx){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            private boolean isSuccessful = false;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(ctx,"","正在提交数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                isSuccessful = uploadCustomerInfo(customerInfo,SQLiteUtils.getInstance(ctx).getDbUtils());
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(isSuccessful){
                    Toast.makeText(ctx,"添加成功!",Toast.LENGTH_SHORT).show();
                    goBack();//页面返回
//                    final MessageBox msgBox = new MessageBox(ctx);
//                    msgBox.setMessage("添加客户成功!是否继续添加联系人？");
//                    msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            switch(v.getId()){
//                                case MessageBox.ID_DIALOG_BUTTON_CANCEL://取消操作
//                                    msgBox.dismiss();
//                                    goBack();
//                                    break;
//                                case MessageBox.ID_DIALOG_BUTTON_OK:
//                                    gotoNewContractorPage();//跳转到添加联系人的页面
//                                    break;
//                            }
//                        }
//                    });
//                    msgBox.show();
                }else{
                    Toast.makeText(ctx,"添加客户失败!请检查输入的数据!",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 跳转到添加联系人的页面
     */
    public void gotoNewContractorPage(){
        int kh_id = 0;//客户ID
        String khName = "";//客户名称
        try{
            CustomerTable customer = SQLiteUtils.getInstance(NewCustomerActivity.this)
                    .getDbUtils().findFirst(Selector.from(CustomerTable.class)
                            .orderBy("cid",true));//查询最后一个客户的ID
            if(customer!=null){
                kh_id = customer.id;
                khName = customer.mc;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(kh_id <= 0){
            Toast.makeText(NewCustomerActivity.this,"系统错误!",Toast.LENGTH_SHORT).show();
            NewCustomerActivity.this.finish();
            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            return;
        }
        Intent intent = new Intent(NewCustomerActivity.this,NewContractorActivity.class);
        intent.putExtra("customerId",kh_id);
        intent.putExtra("customerName",khName);
        startActivity(intent);
        NewCustomerActivity.this.finish();
    }

    /**
     * 上传客户数据
     * @param model
     */
    public boolean uploadCustomerInfo(CustomerInfoModel model,DbUtils dbUtils){
        boolean isOk = true;
        try {
            CustomerTable customer = new CustomerTable();
            //客户数据
            customer.mc =  model.customerName;
            customer.lxr = model.contractor;
            customer.kjj = StringUtils.getFirstLetterString(model.customerName);
            customer.jg_mc = "发出价";//默认为发出价
            customer.jc = model.customerName;
            customer.djbz = 0;
            customer.dh = model.connectity;
            customer.id = 0;
            customer.state = 1;//表示该是新增客户
            //收货地址数据
            DeliverGoodsTable item = new DeliverGoodsTable();
            item.id = 0;
            item.kh_id = 0;
            item.djbz = 0;
            item.dq_id = model.intCarea;
            item.jc = model.abbr;
            if (SystemData.currentLocation != null) {
                item.jwd = SystemData.currentLocation.getLatitude() + ","
                        + SystemData.currentLocation.getLongitude();
            }
            item.jymj = TextUtils.isEmpty(model.addrArea) ? 0 : Integer.parseInt(model.addrArea);
            item.khlx = model.intCtype;
            item.shdh = model.connectity;
            item.shdz = model.addr;
            item.shfs = 2;//暂时默认为2
            item.shr = model.contractor;
            isOk = uploadCustomerInfo(customer,item,dbUtils);//上传客户及收货地址
        }catch (Exception e){
            e.printStackTrace();
            isOk = false;
        }
        return isOk;
    }

    /**
     * 上传客户及收货地址，如果失败则直接存入本地
     */
    public static boolean uploadCustomerInfo(final CustomerTable customer,final DeliverGoodsTable deliver, final DbUtils dbUtils)throws Exception{
        HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
        String methodName = "Cx_AddKehu";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("khmc", customer.mc);
        jsonObject.put("shdz", deliver.shdz);
        jsonObject.put("jc", deliver.jc);
        jsonObject.put("khlx", deliver.khlx);
        jsonObject.put("dq_id", deliver.dq_id);
        jsonObject.put("shr", deliver.shr);
        jsonObject.put("shdh", deliver.shdh);
        jsonObject.put("jymj", deliver.jymj);
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"addKh\":" + jsonObject.toString() + "}}";
        System.out.println("-----> 正在上传客户及收货地址数据：" + messageBody);
        RequestParams params = new RequestParams("UTF-8");
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
        String result = FileUtils.stream2string(is, "utf-8");
        System.out.println("----->上传客户及收货地址结果：" + result);
        if (!TextUtils.isEmpty(result)) {
            BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
            if (resultModel.Result.equals("0000")) {
                boolean isOk = true;
                SQLiteDatabase database = dbUtils.getDatabase();
                try{
                    database.beginTransaction();
                    JSONObject jobj = new JSONObject(resultModel.Data);
                    int kh_id = jobj.getInt("kh_id");
                    int shdz_id = jobj.getInt("shdz_id");
                    customer.id = kh_id;
                    customer.state = 0;//更新客户状态
                    dbUtils.save(customer);//保存客户数据
                    deliver.kh_id = kh_id;//重置客户ID
                    deliver.id = shdz_id;//重置网络收货地址ID
                    dbUtils.save(deliver);//保存客户收货地址数据
                    database.setTransactionSuccessful();//上传成功则设置事务处理成功
                }catch (Exception e){
                    isOk = false;
                    e.printStackTrace();
                }
                database.endTransaction();
                return isOk;
            }
        }
        return false;
    }

    /**
     * 检测客户名称是否已经存在
     * @param customerName
     * @return
     */
    public boolean isCustomerExists(String customerName){
        try {
            CustomerTable customer = SQLiteUtils.getInstance(this).getDbUtils()
                    .findFirst(Selector.from(CustomerTable.class).where("mc", "=", customerName));
            return customer!=null?true:false;
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 参数检测
     * @return
     */
    public boolean checkArguments(){
        if(etCustomerName.getText().length()<=0){
            Toast.makeText(this,"请输入客户名称!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(isCustomerExists(etCustomerName.getText().toString())){
            Toast.makeText(this,"客户名称已存在!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etAddress.getText().length()<=0){
            Toast.makeText(this,"请输入收货地址!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etAbbrviation.getText().length()<=0){
            Toast.makeText(this,"请输入收货地址简称!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etContractorName.getText().length()<=0){
            Toast.makeText(this,"请输入收货人!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etConnectity.getText().length()<=0){
            Toast.makeText(this,"请输入联系方式!",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 初始化操作
     * @param context
     */
    public void init(final Context context){
        new AsyncTask<Void,Void,Void>(){
            //客户类型数组
            private String[] ctypeArr = null;
            private int[] intCtypeArr = null;
            //客户地区数组
            private String[] careaArr = null;
            private int[] intCareaArr = null;
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    DbUtils dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                    List<CustomerTypeTable> ctypelist = dbUtils.findAll(CustomerTypeTable.class);
                    if(ctypelist!=null && ctypelist.size()>0){
                        ctypeArr = new String[ctypelist.size()];
                        intCtypeArr = new int[ctypeArr.length];
                        for(int i=0;i<ctypelist.size();i++){
                            CustomerTypeTable item = ctypelist.get(i);
                            ctypeArr[i] = item.khlx;
                            intCtypeArr[i] = item.id;
                        }
                    }
                    List<CustomerAreaTable> carealist = dbUtils.findAll(CustomerAreaTable.class);
                    if(carealist!=null && carealist.size()>0){
                        careaArr = new String[carealist.size()];
                        intCareaArr = new int[careaArr.length];
                        for(int i=0;i<carealist.size();i++){
                            CustomerAreaTable item = carealist.get(i);
                            careaArr[i] = item.mc;
                            intCareaArr[i] = item.id;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                dealResult();//处理查询结果
            }

            /**
             * 处理查询结果
             */
            public void dealResult(){
                if(ctypeArr!=null && ctypeArr.length>0) {
                    if(customerInfo.intCtype == 0){
                        customerInfo.intCtype = intCtypeArr[0];
                        customerInfo.ctype = ctypeArr[0];
                        txtCustomerType.setText(ctypeArr[0]);
                    }
                    txtCustomerType.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new AlertDialog.Builder(context).setItems(ctypeArr, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    txtCustomerType.setText(ctypeArr[which]);
                                    customerInfo.intCtype = intCtypeArr[which];
                                    customerInfo.ctype = ctypeArr[which];
                                }
                            }).show();
                        }
                    });
                }
                if(careaArr!=null && careaArr.length>0) {
                    if(customerInfo.intCarea == 0){
                        customerInfo.intCarea = intCareaArr[0];
                        customerInfo.carea = careaArr[0];
                        txtCustomerArea.setText(careaArr[0]);
                    }
                    txtCustomerArea.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new AlertDialog.Builder(context).setItems(careaArr, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    txtCustomerArea.setText(careaArr[which]);
                                    customerInfo.intCarea = intCareaArr[which];
                                    customerInfo.carea = careaArr[which];
                                }
                            }).show();
                        }
                    });
                }
            }
        }.execute();
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pnewCustomer_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
